// pages/profile_edit/profile_edit.js
const http = require('../../utils/http')
const api = require('../../utils/api')
const ui = require('../../utils/ui')
const qiniuUploader = require("../../sdk/qiniuUploader");

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({

  initQiniu(token) {
    var options = {
      region: 'SCN', //华南必须对应
      uptoken: token,
      shouldUseQiniuFileName: false
    };
    // 将七牛云相关配置初始化进本sdk
    qiniuUploader.init(options);
  },


  submit(params) {
    http.request({
      url: api.modeInfo,
      method: "POST",
      data: params
    }).then(res => {
      console.log(res)
      ui.hideLoading()
      ui.showToast({
        title: '修改成功',
      })
    })
  },

  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    console.log(avatarUrl)

    this.setData({
      'imageObject': {},
      'imageProgress': {}
    });

    // 向七牛云上传
    ui.showLoading();
    qiniuUploader.upload(avatarUrl, (res) => {
        this.setData({
          avatarUrl,
          'imageObject': res
        });
        this.submit({
          id: getApp().globalData.memberId,
          face: "http://qiniu-image.wrzztech.top/"+res.fileURL
        })
        console.log('file url is: ' + res.fileURL);
      }, (error) => {
        ui.hideLoading()
        console.error('error: ' + JSON.stringify(error));
      },
      null,
      (progress) => {
        this.setData({
          'imageProgress': progress
        });
        console.log('上传进度', progress.progress);
        console.log('已经上传的数据长度', progress.totalBytesSent);
        console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend);
      }, cancelTask => this.setData({
        cancelTask
      })
    );
  },

  bindChange(e) {
    let newName = e.detail.value
    if (newName != this.data.nickName && newName.length > 0) {
      this.submit({
        id: getApp().globalData.memberId,
        nickName: e.detail.value
      })
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    nickName: "",
    avatarUrl: defaultAvatarUrl,
    theme: wx.getSystemInfoSync().theme,
    // uptoken: null,
    // 图片上传（从相册）返回对象。上传完成后，此属性被赋值
    imageObject: {},
    // 图片上传（从相册）进度对象。开始上传后，此属性被赋值
    imageProgress: {},
    // 此属性在qiniuUploader.upload()中被赋值，用于中断上传
    cancelTask: function () {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    http.request({
      url: api.qiniuToken,
      method: "GET",
    }).then(res => {
      console.log(res)
      let token = res.data.result
      if (token != null && token != "") {
        this.initQiniu(token)
      }
    })
    this.setData({
      nickName: options.nickName,
      avatarUrl: options.face
    })
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})